/**
 * 用户模型配置服务 - 从后端加载用户保存的模型配置
 */
import { message } from 'antd';

// 使用相对路径，让Vite代理处理
const API_BASE = '';

export interface UserModel {
  id: string;
  name: string;
  displayName: string;
  provider: string;
  providerName: string;
  modelName: string;
  baseUrl: string;
  apiKey: string;
  status: string;
  enabled: boolean;
  temperature?: number;
  maxTokens?: number;
  topP?: number;
  stream?: boolean;
}

// 后端返回的原始数据格式（蛇形命名）
interface BackendModel {
  id: string;
  name: string;
  provider: string;
  model_name: string;
  api_base: string;
  api_key: string;
  status: string;
  enabled: boolean;
  temperature?: number;
  max_tokens?: number;
  top_p?: number;
  stream?: boolean;
}

class UserModelsService {
  private cache: UserModel[] | null = null;
  private lastFetch: number = 0;
  private cacheTimeout = 60000; // 1分钟缓存

  /**
   * 转换后端数据格式为前端格式
   */
  private transformModel(backendModel: BackendModel): UserModel {
    // 提供商名称映射
    const providerNames: Record<string, string> = {
      openai: 'OpenAI',
      claude: 'Anthropic',
      deepseek: 'DeepSeek',
      doubao: '豆包',
      qwen: '通义千问',
      glm: '智谱AI',
    };

    return {
      id: backendModel.id,
      name: backendModel.name,
      displayName: backendModel.name,
      provider: backendModel.provider,
      providerName: providerNames[backendModel.provider] || backendModel.provider,
      modelName: backendModel.model_name,
      baseUrl: backendModel.api_base,
      apiKey: backendModel.api_key,
      status: backendModel.status,
      enabled: backendModel.enabled,
      temperature: backendModel.temperature,
      maxTokens: backendModel.max_tokens,
      topP: backendModel.top_p,
      stream: backendModel.stream,
    };
  }

  /**
   * 获取用户的可用模型列表
   */
  async getAvailableModels(forceRefresh = false): Promise<UserModel[]> {
    // 检查缓存
    if (!forceRefresh && this.cache && (Date.now() - this.lastFetch) < this.cacheTimeout) {
      return this.cache;
    }

    try {
      const response = await fetch(`${API_BASE}/api/v1/model-configs`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const backendModels: BackendModel[] = await response.json();

      // 转换为前端格式
      const models = backendModels.map(m => this.transformModel(m));

      // 更新缓存
      this.cache = models;
      this.lastFetch = Date.now();

      console.log(`Loaded ${models.length} user models from backend`);

      return models;
    } catch (error) {
      console.error('Failed to fetch user models:', error);
      message.error('获取模型列表失败');

      // 返回缓存数据（如果有）
      return this.cache || [];
    }
  }

  /**
   * 清除缓存
   */
  clearCache(): void {
    this.cache = null;
    this.lastFetch = 0;
  }

  /**
   * 获取单个模型配置
   */
  async getModelById(modelId: string): Promise<UserModel | null> {
    const models = await this.getAvailableModels();
    return models.find(m => m.id === modelId) || null;
  }

  /**
   * 测试模型连接
   */
  async testModelConnection(model: Partial<UserModel>): Promise<boolean> {
    try {
      const token = localStorage.getItem('authToken');
      if (!token) {
        message.error('请先登录');
        return false;
      }

      const response = await fetch(`${API_BASE}/model-configs/test`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          baseUrl: model.baseUrl,
          apiKey: model.apiKey,
          modelName: model.modelName,
          providerId: model.provider,
          displayName: model.displayName
        })
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();

      if (result.success) {
        message.success('模型连接成功');
        // 清除缓存，下次重新加载
        this.clearCache();
      } else {
        message.error(result.message || '模型连接失败');
      }

      return result.success;
    } catch (error) {
      console.error('Failed to test model connection:', error);
      message.error('测试连接失败');
      return false;
    }
  }

  /**
   * 格式化模型用于对话API调用
   */
  formatModelForChat(model: UserModel): any {
    return {
      model: model.modelName,
      provider: model.provider,
      api_key: model.apiKey,
      api_base: model.baseUrl,
      temperature: model.temperature || 0.7,
      max_tokens: model.maxTokens || 2000,
      top_p: model.topP || 1.0,
      stream: model.stream !== false
    };
  }
}

export default new UserModelsService();
